<?php
namespace Frieza\Modules\Topic\Controllers;

use Illuminate\Support\MessageBag;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use App\Admin\Extensions\Tools\UserButton;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\TopicBanner;
use Doraemon\tools\ImgUrl;
use Doraemon\service\position\UserProfileModule;
use Doraemon\service\position\AdmOperationModule;
use Doraemon\model\Position\PositionRules;


class TopicBannerController extends Controller
{
    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    private function _filterWhere($params){
        if(isset($params['_columns_'])){
            unset($params['_columns_']);
        }
        if(isset($params['_pjax'])){
            unset($params['_pjax']);
        }
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['per_page']) ? $params['per_page'] : self::PAGE_SIZE;
        $limit = [($page - 1) * $pageSize, $pageSize];
        unset($params['page']);
        $where = [];
        foreach ($params as $_k => &$_v) {
            if ($_v <> '') {
                $where[$_k] = $_v;
            }
        }
        $data = [
            'LIMIT' => $limit,
        ];

        if (!empty($where)) {
            $data['AND'] = $where;
        }

        return $data;
    }

    public function index(Request $request, Content $content, $id)
    {
        $request = $request->all();

        $request = self::_filterWhere($request);
        return $content
            ->header('Banner管理')
            ->breadcrumb(
                ['text' => '话题管理', 'url' => '/topic/index'],
                ['text' => '话题Banner管理', 'url' => '/topic/topicbanner/'.$id]
            )
            ->row('话题id为：'.$id)
            ->body(self::listAction($request, $id));
    }

    public function listAction($request, $id)
    {
        $banner_list = TopicBanner::getBannerListsByTopicId($id);
        $banner_ids = array_column($banner_list, 'id');
        $taskRules = AdmOperationModule::getPositionRulesById($banner_ids, PositionRules::MODULE_TYPE_TOPIC_BANNER);
        foreach ($banner_list as &$row) {
            $row['user_profile'] = $taskRules[$row['id']] ?? [];
        }
        $gridModel = new pGridDataModel($banner_list, count($banner_list), [
            'perPage' => $request['per_page'] ? : $request['LIMIT'][1]
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableFilter();
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disablePagination();

            $grid->column('id', 'banner_id')->width(100);
            $grid->column('topic_id', '话题id')->width(100);
            $grid->column('pic_id', 'banner信息')->display(function() {
                return "<img src=".ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $this->pic_id, ImgUrl::IMAGE_SIZE_ORI_NPHONE)." width='200' /><br/>"."banner始时间：".$this->start_time."<br/>"."banner结束时间".$this->end_time;
            });
            $grid->column('user_profile', '分群信息')->userProfile();
            $grid->column('addtime', '添加时间')->display(function() {
                return $this->addtime;
            });

        });

        $list = $listGrid->render();

        return $list;
    }

    public function add(Request $request, Content $content, $id)
    {

        $request = $request->all();
        return $content
            ->header('话题管理')
            ->breadcrumb(
                ['text' => '话题banner管理', 'url' => '/topic/topicbanner/'.$id],
                ['text' => '添加banner', 'url' => '/topic/topicbanner/'.$id.'/create']
            )
            ->body(self::editAction($request, $banner_id = 0, $id ));

    }

    public function edit(Request $request, Content $content, $id, $banner_id)
    {

        $request = $request->all();
        return $content
            ->header('话题管理')
            ->breadcrumb(
                ['text' => '话题banner管理', 'url' => '/topic/topicbanner/'.$id],
                ['text' => '修改banner', 'url' => '/topic/topicbanner/'.$id.'/'.$banner_id.'/edit']
            )
            ->body(self::editAction($request, $banner_id, $id));


    }

    public function editAction($request, $banner_id, $id)
    {
        $data = [];
        $data['topic_id'] = $id;
        if($banner_id != 0) {
            //修改
            $data = TopicBanner::getById($banner_id);
            if(isset($data['link_type']) && $data['link_type']) {
                $data['banner_link'] = [
                    'link_type' => $data['link_type'],
                    'link_params' => $data['link_params']
                ];
            }
            $data['user_profile'] = AdmOperationModule::getPositionRulesById($banner_id, PositionRules::MODULE_TYPE_TOPIC_BANNER, true) ?: [];
            $form = new Form($data);
            $form->hidden('id');
        } else {
            //添加
            $form = new Form($data);
        }
        $form->hidden('topic_id');

        $form->imgUpload('pic_id', 'banner图片', false, ['imgType' => ImgUrl::APPTYPE_OP, 'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI]);
        $form->datetime('start_time', 'banner开始展示时间');
        $form->datetime('end_time', 'banner结束展示时间');
        $form->linkSelect('banner_link', 'banner跳转链接');
        $form->userProfile('user_profile', '用户分群')->generate();
        $form->action('/admin/topic/topicbanner/save');

        return $form->render();
    }

    public function editSubmit(Request $request, Content $content)
    {
        $request = $request->all();
        $data = [];
        $data['topic_id'] = $request['topic_id'];
        $data['pic_id'] = $request['pic_id'];
        $data['link_type'] = $request['link_type'];
        $data['link_params'] = json_encode($request['link_params'], JSON_UNESCAPED_UNICODE);
        $data['start_time'] = $request['start_time'];
        $data['end_time'] = $request['end_time'];
        $data['admin_id'] = Admin::user()->id;
        //分群信息
        $userProfile = $request['user_profile'];

        if(isset($request['id']) && $request['id']) {
            //修改
            $data['edittime'] = date('Y-m-d H:i:s', time());
            $rs = TopicBanner::updateById($request['id'], $data);
        } else {
            //添加
            $data['addtime'] = date('Y-m-d H:i:s', time());
            $rs = TopicBanner::add($data);
            $request['id'] = $rs;
        }
        if($rs) {
            //更新用户分群
            AdmOperationModule::addUserProfile($request['id'], $userProfile, PositionRules::MODULE_TYPE_TOPIC_BANNER);
            $success = new MessageBag([
                'title' => '提交成功'
            ]);
            return redirect('/admin/topic/topicbanner/'.$data['topic_id'])->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '提交失败'
            ]);
            return redirect('/admin/topic/topicbanner/'.$data['topic_id'])->with(compact('error'));
        }


    }

    public function del($topic_id, $banner_id)
    {
        $data = TopicBanner::getById($banner_id);
        if($data) {
            $data['is_delete'] = 1;
            $data['edittime'] = date('Y-m-d H:i:s', time());
            $data['admin_id'] = Admin::user()->id;
            $rs = TopicBanner::updateById($banner_id, $data);
            if($rs) {
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "操作失败",
                ]);
            }
        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }


    }


}